package com.sprite.utils.io;

import com.sprite.utils.UtilURL;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.charset.Charset;

/**
 * @author Jack
 */
public class UtilIO {

    /**
     * 读取io
     *
     * @param in
     *         io流
     * @return 字节数组
     * @throws IOException
     *         io错误
     */
    public static byte[] readToBytes(InputStream in) throws IOException {
        ByteBuffer byteBuffer = new ByteBuffer();

        byte[] bts = new byte[512];

        int size = 0;
        while ((size = in.read(bts)) > 0) {
            byteBuffer.append(bts, size);
        }

        return byteBuffer.toByteArray();
    }

    public static String readToText(InputStream in, String charsetName) throws IOException {
        Reader reader = new InputStreamReader(in, charsetName == null ? Charset.defaultCharset().name() : charsetName);

        StringBuilder text = new StringBuilder();
        char[] cbuf = new char[512];
        int lg = 0;
        while ((lg = reader.read(cbuf)) > 0) {
            text.append(cbuf, 0, lg);
        }

        return text.toString();
    }

    public static void write(InputStream in, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[512];

        int lg = 0;
        while ((lg = in.read(buffer)) > 0) {
            outputStream.write(buffer, 0, lg);
        }
    }

    public static void main(String[] args) throws Exception{
        byte[] bts =  readToBytes(UtilURL.fromUrlString("https://www.cnblogs.com/gqymy/p/9216713.html").openStream());
        System.out.println(bts);
    }
}
